package com.mengniu.commerce.collect.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mengniu.commerce.admin.api.RemoteStoreService;
import com.mengniu.commerce.admin.api.domain.SysStore;
import com.mengniu.commerce.common.core.config.RestTemplateConfig;
import com.mengniu.commerce.common.core.constant.Constants;
import com.mengniu.commerce.common.core.domain.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.*;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author 13754
 */
@Component
@Slf4j
public class RestTemplateUtil {

   @Resource
   RestTemplateConfig restTemplateConfig;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RemoteStoreService remoteStoreService;


    public String getToken(Long bosId) {

        String clientId ="";
        String clientSecret ="";
        if (stringRedisTemplate.hasKey(bosId+"_TOKEN")){
            String token = redisTemplate.opsForValue().get(bosId+"_TOKEN").toString();
            if (!StringUtils.isEmpty(token)){
                return token;
            }
        }
        R<SysStore> storeInfo = remoteStoreService.getStoreInfo(String.valueOf(bosId),"微盟");
        if (Constants.SUCCESS == storeInfo.getCode()){
            clientId = storeInfo.getData().getClientId();
            clientSecret = storeInfo.getData().getClientSecret();
        }

        String baseUrl = "https://dopen.weimob.com/fuwu/b/oauth2/token";

        String grantType="client_credentials";

        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl)
                .queryParam("grant_type", grantType)
                .queryParam("client_id", clientId)
                .queryParam("client_secret", clientSecret);
        ClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        ResponseEntity<String> response = restTemplateConfig.restTemplate(factory).exchange(builder.toUriString(), HttpMethod.POST, null, String.class);
        String responseBody = response.getBody();
        System.out.println(responseBody);
        JSONObject jsonObject =  JSONObject.parseObject(responseBody);
        String token = jsonObject.get("access_token").toString();
        redisTemplate.opsForValue().set(bosId+"_TOKEN",token,110L, TimeUnit.MINUTES);
        return token;
    }

    /***
     * 向三方发起请求（json形式）
     * @param
     * @param
     * ***/
    public String doPost(JSONObject args, String uri,String token) {
        long startTime = System.currentTimeMillis();
        ClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        try {
            HttpHeaders requestHeaders = new HttpHeaders();
            UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(uri)
                    .queryParam("accesstoken", token);
            requestHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
            HttpEntity<String> requestEntity = new HttpEntity<>(args.toJSONString(), requestHeaders);
            ResponseEntity<String> responseResult = restTemplateConfig.restTemplate(factory).exchange(builder.toUriString(), HttpMethod.POST, requestEntity, String.class);
            long endTime = System.currentTimeMillis();
            String res = responseResult.getBody();
            log.info("\r\n请求三方：" + uri + "，\n参数：\n" + args + "\n返回结果：\n" + JSON.toJSONString(res) + ", 三方请求耗时:" + (endTime - startTime));
            if (res != null) {
                return res;
            }
        } catch (Exception e) {
            log.error("向第三方平台提交数据出错" + "\nURL:" + uri + "\n参数：" + args + ":" + e);
        }
        return null;
    }



}
